//
//  MPTReadyLiveView.m
//  MPTLive
//
//  Created by caixun on 15/8/18.
//  Copyright (c) 2015年 Jeakin. All rights reserved.
//

#import "MPTReadyLiveView.h"
#import "MPTHttpClient.h"
#import "MPTConfig.h"
#import "MPTLocationModel.h"
#import <CoreLocation/CoreLocation.h>
#import "UIColor+MPTColor.h"
#import "UIFont+MPTFont.h"
#import "ActionSheetVIew.h"
#import "EditImageView.h"
#import "MPTLiveIMManager.h"


#define MPTRLive_TextViewPlaceHolder @"快告诉大家直播什么..."
#define MPTRLive_LocationText @"地理位置识别中..."
#define MPTRLive_CloseLocationText @"开普勒452b行星(离地球不远)"
#define MPTRLive_StartBtn_Title @"开始直播"
#define MPTRLive_MyHomeBtn_Title @"进入个人主页"

// 页面上准备直播图片距离屏幕左边距离
#define MPTRLive_Image_LeftSpace (11)
// 页面上准备直播图片距离屏幕上边距离
#define MPTRLive_Image_TopSpace (25)

// 文本框距离屏幕左边距离
#define MPTRLive_TextView_LeftSpace (5)
// 文本框与上面直播图片之间的间距
#define MPTRLive_TextView_Image_Space (15)
// 当前位置距离屏幕左边距离
#define MPTRLive_Location_LeftSpace (20)

// 个人中心按钮距离屏幕底部距离
#define MPTRLive_Bottom_Space (20)
// 个人中心按钮和开始直播按钮的间距
#define MPTRLive_Btn_Space (10)
// 开始直播按钮和地理位置的间距
#define MPTRLive_startBtn_Location_Space (20)


@interface MPTReadyLiveView ()
<UITextViewDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
AMapSearchDelegate,
AMapLocationManagerDelegate>

@property (nonatomic, strong) UITextView *textView;
// textview的placeholder
@property (nonatomic, strong) UILabel *labPlaceHolder;
// 用户当前地址
@property (nonatomic, strong) UILabel *labLocation;
// 开始直播按钮
@property (nonatomic, strong) UIButton *startLiveBtn;
// 进入个人主页按钮
@property (nonatomic, strong) UIButton *myHomeBtn;
// 定位开关
@property (nonatomic, strong) UIButton *switchOpenBtn;
@property (nonatomic, strong) UIButton *switchCloseBtn;
@property (nonatomic, strong) UIImageView *locationImgv;

/// 显示封面的
@property (nonatomic,strong) UIImageView *iamgeVFenMian;

/// 封面上的按钮
@property (nonatomic, strong) UIButton *butFengMian;

/// 封面上的编辑按钮
@property (nonatomic, strong) UIButton *butBianJi;

/// 选择封面时候的提示框
@property (nonatomic, strong) ActionSheetVIew * sheetView;

/// 图片裁剪器
@property (nonatomic, strong) EditImageView *editView;


@end


@implementation MPTReadyLiveView {
    UIImagePickerController *picker;
}


#pragma mark - ***************************** View Lifecycle ***********************************

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initViews]; // 初始化界面
        [self initVariable]; // 初始化变量
    }
    return self;
}

-(void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    if(newSuperview == nil)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [[self subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        return ;
    }
}


#pragma mark - ******************************** Init All Views **********************************

- (void)initVariable
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status)
    {
        self.switchCloseBtn.hidden = NO;
        self.switchOpenBtn.hidden = YES;
        MPTSingleObjectInstance.currentLocation = MPTRLive_CloseLocationText;
        self.labLocation.text = MPTSingleObjectInstance.currentLocation;
        
        MPTSingleObjectInstance.currentLongitude = 0;
        MPTSingleObjectInstance.currentlatitude = 0;
    }
    else
    {
        self.switchCloseBtn.hidden = YES;
        self.switchOpenBtn.hidden = NO;
        
        if([@"nil" isEqualToString:MPTSingleObjectInstance.currentLocation])
        {
            [self req_CurrentLocation];
        }
        else
        {
            if([MPTRLive_CloseLocationText isEqualToString:MPTSingleObjectInstance.currentLocation])
            {
                self.switchCloseBtn.hidden = NO;
                self.switchOpenBtn.hidden = YES;
            }
            else
            {
                self.switchCloseBtn.hidden = YES;
                self.switchOpenBtn.hidden = NO;
            }
            self.labLocation.text = MPTSingleObjectInstance.currentLocation;
        }
    }
}

- (void)initViews
{
    [self initMainViews];
}

- (void)initMainViews
{
    
    //右侧x标示
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    closeButton.frame =CGRectMake(self.frame.size.width - 42, 22, 30, 30);
    UIImage *closeButtonImage = [UIImage imageNamed:@"general_btn_close_normal"];
    [closeButton setImage:[UIImage imageNamed:@"general_btn_close_normal_pressed"] forState:UIControlStateHighlighted];
    [closeButton addTarget:self action:@selector(closeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:closeButtonImage forState:UIControlStateNormal];
    [self addSubview:closeButton];
    
    // 半透的遮罩
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:self.frame];
    bgImageView.backgroundColor =[UIColor colorWithWhite:0 alpha:0.5];
    [self addSubview:bgImageView];
    
    /// 封面的相框
    _iamgeVFenMian = [[UIImageView alloc] initWithFrame:CGRectMake(30 , (screenH - screenW - 60) / 2, screenW - 60, screenW - 60)];
    UIImage *image =[UIImage imageNamed:@"xuxiankuang"];
    
    /// 适配屏幕
    if (self.frame.size.height != 480)
    {
        _iamgeVFenMian.center = self.center;
    }
    else
    {
        _iamgeVFenMian.frame = CGRectMake(45 ,120, screenW - 90, screenW - 90);
    }

    /// 指定拉伸位置
    [image stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    _iamgeVFenMian.image = image;
    _iamgeVFenMian.clipsToBounds = YES;
    _iamgeVFenMian.layer.cornerRadius = 5;
    _iamgeVFenMian.userInteractionEnabled = YES;
    [self addSubview:_iamgeVFenMian];
    
    /// 傻逼，没事下加啥
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(butFengMianClicked:)];
    [_iamgeVFenMian addGestureRecognizer:tap];
    
    /// 封面上的按钮
    _butFengMian = [UIButton buttonWithType:UIButtonTypeCustom];
    _butFengMian.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _butFengMian.frame = CGRectMake(20, 261 + 78, self.frame.size.width - 40, 18);
    _butFengMian.center = _iamgeVFenMian.center;
    [_butFengMian setImage:[UIImage imageNamed:@"Add"] forState:UIControlStateNormal];
    [_butFengMian setTitle:@"  添加直播封面" forState:UIControlStateNormal];
    [_butFengMian addTarget:self action:@selector(butFengMianClicked:) forControlEvents:UIControlEventTouchUpInside];
    _butFengMian.titleLabel.font = [UIFont systemFontOfSize:16];
    [_butFengMian setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:_butFengMian];
    
    /// 封面上的按钮
    _butBianJi = [UIButton buttonWithType:UIButtonTypeCustom];
    _butBianJi.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _butBianJi.frame = CGRectMake(0, CGRectGetHeight(_iamgeVFenMian.frame) - 43, CGRectGetWidth(_iamgeVFenMian.frame), 43);
    [_butBianJi setTitle:@"编辑直播封面" forState:UIControlStateNormal];
    [_butBianJi addTarget:self action:@selector(butFengMianClicked:) forControlEvents:UIControlEventTouchUpInside];
    _butBianJi.backgroundColor = RGBAAllColor(0x282828, 0.3);
    _butBianJi.titleLabel.font = [UIFont systemFontOfSize:16];
    [_butBianJi setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _butBianJi.hidden = YES;
    [self.iamgeVFenMian addSubview:_butBianJi];
    
    
    UIImage *readyIcon = [UIImage imageNamed:@"LiveReadyIcon"];
    CGRect liveImgeRect = CGRectMake(MPTRLive_Image_LeftSpace,
                                     MPTRLive_Image_TopSpace,
                                     readyIcon.size.width,
                                     readyIcon.size.height);
    UIImageView *readyLiveImge = [[UIImageView alloc] initWithFrame:liveImgeRect];
    readyLiveImge.image = readyIcon;
    [self addSubview:readyLiveImge];
    
    // 准备直播文字
    UILabel *readyLabel = [[UILabel alloc] initWithFrame:CGRectMake(readyLiveImge.frame.origin.x+readyLiveImge.frame.size.width+5, readyLiveImge.frame.origin.y+6, 200, readyLiveImge.frame.size.height-6)];
    readyLabel.text = @"准备直播";
    readyLabel.font = [UIFont YXFontOfSize:10.0f];
    readyLabel.textColor = [UIColor YXColorWithHexCode:@"#ffe200"];
    [self addSubview:readyLabel];
    
    // 开始直播按钮
    CGRect startRect = CGRectMake(MPTRLive_Location_LeftSpace,
                                               screenH-MPTRLive_Bottom_Space-44,
                                               screenW-MPTRLive_Location_LeftSpace*2,
                                               44);
    self.startLiveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startLiveBtn.frame = startRect;
    [self.startLiveBtn setTitle:MPTRLive_StartBtn_Title forState:UIControlStateNormal];
    [self.startLiveBtn setBackgroundColor:[UIColor YXColorWithHexCode:@"#ffe200"]];
    self.startLiveBtn.layer.cornerRadius = 22;
    self.startLiveBtn.titleLabel.font = [UIFont YXFontOfSize:16.0f];
    [self.startLiveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.startLiveBtn.clipsToBounds = YES;
    [self addSubview:self.startLiveBtn];
    
    // 地理位置文字前面的图片
    UIImage *locationImg = [UIImage imageNamed:@"LocationImg_Open"];
    CGRect locationImgRect = CGRectMake(MPTRLive_Location_LeftSpace,
                                         self.startLiveBtn.frame.origin.y-MPTRLive_startBtn_Location_Space-20,
                                         locationImg.size.width,
                                         locationImg.size.height);
    self.locationImgv = [[UIImageView alloc] initWithFrame:locationImgRect];
    self.locationImgv.image = locationImg;
    [self addSubview:self.locationImgv];
    
    // 地理位置开关
    UIImage *switchOpen = [UIImage imageNamed:@"SwitchOpen"];
    self.switchOpenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.switchOpenBtn.frame = CGRectMake(screenW-20-switchOpen.size.width,
                                          self.locationImgv.frame.origin.y - 5,
                                          switchOpen.size.width,
                                          switchOpen.size.height);
    [self.switchOpenBtn addTarget:self action:@selector(onClickForLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.switchOpenBtn setImage:switchOpen forState:UIControlStateNormal];
    //self.switchOpenBtn.hidden = NO;
    [self addSubview:self.switchOpenBtn];
    
    UIImage *switchClose = [UIImage imageNamed:@"SwitchClose"];
    self.switchCloseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.switchCloseBtn.frame = CGRectMake(screenW-20-switchClose.size.width,
                                           self.locationImgv.frame.origin.y - 5,
                                           switchClose.size.width,
                                           switchClose.size.height);
    [self.switchCloseBtn addTarget:self action:@selector(onClickForLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.switchCloseBtn setImage:switchClose forState:UIControlStateNormal];
    //self.switchCloseBtn.hidden = YES;
    [self addSubview:self.switchCloseBtn];
    
    // 用户当前地理位置
    CGRect locationRect = CGRectMake(self.locationImgv.frame.origin.x+self.locationImgv.frame.size.width+5,
                                     self.startLiveBtn.frame.origin.y-MPTRLive_startBtn_Location_Space-20,
                                     screenW-MPTRLive_TextView_LeftSpace*2-self.locationImgv.frame.origin.x-self.locationImgv.frame.size.width-5-self.switchCloseBtn.frame.size.width-10,
                                     self.locationImgv.frame.size.height);
    self.labLocation = [[UILabel alloc] initWithFrame:locationRect];
    self.labLocation.text = MPTRLive_LocationText;
    self.labLocation.font = [UIFont YXFontOfSize:12.0f];
    self.labLocation.enabled = YES;
    self.labLocation.textColor= [UIColor colorWithRed:254/255.0f green:254/255.0f blue:254/255.0f alpha:1.0f];
    self.labLocation.backgroundColor = [UIColor clearColor];
    [self addSubview:self.labLocation];
    
    // 创建文本框
    CGRect textViewRect = CGRectMake(MPTRLive_TextView_LeftSpace,
                                     readyLiveImge.frame.origin.y+readyLiveImge.frame.size.height+MPTRLive_TextView_Image_Space,
                                     screenW-MPTRLive_TextView_LeftSpace*2,
                                     70);
    self.textView = [[UITextView alloc] initWithFrame:textViewRect];
    self.textView.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.5f];
    self.textView.font = [UIFont YXFontOfSize:20.0f];
    self.textView.delegate = self;
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.returnKeyType = UIReturnKeyDone;
    self.textView.scrollEnabled = NO;
    [self addSubview:self.textView];
    
    // 创建textview的placeholder
    CGRect placeHolderRect = CGRectMake(self.textView.frame.origin.x+5,
                                        self.textView.frame.origin.y + 3,
                                        screenW-(self.textView.frame.origin.x+5)*2,
                                        30);
    self.labPlaceHolder = [[UILabel alloc] initWithFrame:placeHolderRect];
    self.labPlaceHolder.text = MPTRLive_TextViewPlaceHolder;
    self.labPlaceHolder.enabled = NO;
    self.labPlaceHolder.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.5f];
    self.labPlaceHolder.font = [UIFont YXFontOfSize:20.0f];
    self.labPlaceHolder.backgroundColor = [UIColor clearColor];
    [self addSubview:self.labPlaceHolder];
}


#pragma mark - ****************************** Functions *********************************

- (void)setTargetForBtn:(id)target
        withStartAction:(SEL)startAction
       withMyHomeAction:(SEL)myHomeAction
{
    [self.myHomeBtn addTarget:target action:myHomeAction forControlEvents:UIControlEventTouchUpInside];
    [self.startLiveBtn addTarget:target action:startAction forControlEvents:UIControlEventTouchUpInside];
}

- (NSString *)getTextViewValue
{
    return self.textView.text;
}


#pragma mark - ********************** Delegate *****************************

-(void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 16 && textView.markedTextRange == nil)
    {
        textView.text = [textView.text substringToIndex:16];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.labPlaceHolder.text = @"";
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length == 0)
    {
        self.labPlaceHolder.text = MPTRLive_TextViewPlaceHolder;
    }
    else
    {
        self.labPlaceHolder.text = @"";
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // 点击键盘上完成按钮时触发
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    
    /// 记录原来的
    NSString *strTemp = textView.text;
    
    
    NSString *string = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    if ([string length] > 16 && textView.markedTextRange == nil)
    {
        // 改回原来的
        textView.text = strTemp;
        return NO;
    }
    else
    {
        return YES;
    }
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    [self.textView resignFirstResponder];
}

// TODO: 选择照片的代理
- (void)imagePickerController:(UIImagePickerController *)apicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    /// 获取图片后创建图片裁剪器
    _editView = [[EditImageView alloc] initWithFrame:self.frame Editiamge:image];
    [self addSubview:_editView];
    
    /// 根据值判断点击的是不是 选择
    __weak MPTReadyLiveView *selfWeak = self;
    _editView.block =^(NSInteger intTag)
    {
        [selfWeak userImage];
    };

    /// 回收选择框
    [_sheetView removeFromSuperview];
    [apicker dismissViewControllerAnimated:YES completion:nil];
    
    if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion floatValue] < 9.0)
    {
        [self performSelector:@selector(startCaptureSession) withObject:self afterDelay:1.0];
    }
    else
    {
        [self startCaptureSession];
    }
    picker = nil;
}

- (void)startCaptureSession
{
     [self.vc.session startCaptureSession];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)apicker
{
//
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self performSelector:@selector(startCaptureSession) withObject:self afterDelay:0.5];
    /// 回收选择框
    [_sheetView removeFromSuperview];
    picker = nil;
}

/// 获取图片后进行处理
- (void)userImage
{
    /// 隐藏封面的按钮
    _butFengMian.hidden = YES;
    /// 显示编辑按钮
    _butBianJi.hidden = NO;
    /// 获取图片
    _imageFengMian = [_editView getEditImage];
    /// 显示图片
    _iamgeVFenMian.image = _imageFengMian;
    
    [_editView removeFromSuperview];
}

#pragma mark - ****************************** Button Touch Event ********************************

/// 最开始的关闭
- (void)closeButtonClicked:(UIButton *)button
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpToNav0" object:nil];
}

- (void)onClickForLocation:(id)sender
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status)
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法获取您的位置，请检查定位服务是否开启"
                              message:@""
                              delegate:self
                              cancelButtonTitle:@"确定"
                              otherButtonTitles:nil,nil];
        [alert show];
        
        self.switchCloseBtn.hidden = NO;
        self.switchOpenBtn.hidden = YES;
        MPTSingleObjectInstance.currentLocation = MPTRLive_CloseLocationText;
        self.labLocation.text = MPTSingleObjectInstance.currentLocation;
        self.labLocation.enabled = NO;
        self.locationImgv.image = [UIImage imageNamed:@"LocationImg_Close"];
        
        MPTSingleObjectInstance.currentLongitude = 0;
        MPTSingleObjectInstance.currentlatitude = 0;
    }
    else
    {
        self.switchCloseBtn.hidden = !self.switchCloseBtn.hidden;
        self.switchOpenBtn.hidden = !self.switchOpenBtn.hidden;
        
        if(self.switchOpenBtn.hidden == YES)
        {
            self.labLocation.enabled = NO;
            MPTSingleObjectInstance.currentLocation = MPTRLive_CloseLocationText;
            self.locationImgv.image = [UIImage imageNamed:@"LocationImg_Close"];
            
            MPTSingleObjectInstance.currentLongitude = 0;
            MPTSingleObjectInstance.currentlatitude = 0;
        }
        else
        {
            self.labLocation.enabled = YES;
            MPTSingleObjectInstance.currentLocation = MPTRLive_LocationText;
            [self req_CurrentLocation];
            self.locationImgv.image = [UIImage imageNamed:@"LocationImg_Open"];
        }
        
        self.labLocation.text = MPTSingleObjectInstance.currentLocation;
    }
}


- (void)butFengMianClicked:(id *)but
{
    _sheetView = [[ActionSheetVIew alloc] initWithFrame:self.frame];
    [self addSubview:_sheetView];
    
    __weak MPTReadyLiveView *weakSelf = self;
    
    picker = [UIImagePickerController new];
    __weak typeof(picker) weak_picker = picker;
    _sheetView.block=^(NSInteger intTag)
    {
        /// 拍照
        if (intTag == 1) {
            if (![UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceFront] && ![UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceRear])
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"没找到摄像头"
                                                                message: @"必须需要摄像头"
                                                               delegate: weakSelf
                                                      cancelButtonTitle: @"确定"
                                                      otherButtonTitles: nil];
                [alert show];
                
            }else{
                weak_picker.delegate = weakSelf;
                weak_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                weak_picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                [weakSelf.vc.session stopCaptureSession];
                [weakSelf.vc presentViewController:weak_picker animated:YES completion:nil];
            }
            
        }else if(intTag == 2){
            weak_picker.delegate = weakSelf;
            weak_picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [weakSelf.vc.session stopCaptureSession];
            [weakSelf.vc presentViewController:weak_picker animated:YES completion:nil];
        }
    };
}

#pragma mark - ********************** Net Connection Event *****************************

- (void)req_CurrentLocation
{
    /*
    [MPTSingleObjectInstance.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if(self.switchCloseBtn.hidden == YES && error==nil)
        {
            self.labLocation.text = regeocode.formattedAddress;
            MPTSingleObjectInstance.currentLocation = regeocode.formattedAddress;
            
            MPTSingleObjectInstance.currentLongitude = location.coordinate.longitude;
            MPTSingleObjectInstance.currentlatitude = location.coordinate.latitude;
        }
    }];
     */
    
    MPTSingleObjectInstance.searchAPI.delegate = self;
    MPTSingleObjectInstance.locationManager.delegate = self;
    
    [MPTSingleObjectInstance.locationManager startUpdatingLocation];
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    if(MPTSingleObjectInstance.currentLongitude ==0 && MPTSingleObjectInstance.currentlatitude==0)
    {
        MPTSingleObjectInstance.currentLongitude = location.coordinate.longitude;
        MPTSingleObjectInstance.currentlatitude = location.coordinate.latitude;
        
        [MPTSingleObjectInstance.locationManager stopUpdatingLocation];
        
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
        regeo.radius = 10000;
        regeo.requireExtension = YES;
        
        //发起逆地理编码
        [MPTSingleObjectInstance.searchAPI AMapReGoecodeSearch:regeo];
    }
}

//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        //通过AMapReGeocodeSearchResponse对象处理搜索结果
        
        self.labLocation.text = response.regeocode.formattedAddress;
        MPTSingleObjectInstance.currentLocation = response.regeocode.formattedAddress;
    }
}

@end
